// pages/user/my-registrations/my-registrations.js
const activityItemApi = require('../../../api/activity_item.js')
const util = require('../../../utils/util.js')

Page({
  data: {
    registrations: [],
    loading: false
  },

  onLoad() {
    this.loadMyRegistrations()
  },

  onShow() {
    // 每次显示时刷新数据
    this.loadMyRegistrations()
  },

  async loadMyRegistrations() {
    this.setData({ loading: true })
    
    try {
      const res = await activityItemApi.getUserRegistrations()
      
      if (res.code === 200 || res.success) {
        this.setData({
          registrations: res.data.items || []
        })
        console.log('✅ 加载报名记录成功:', res.data.items?.length || 0)
      }
    } catch (error) {
      console.error('加载报名记录失败:', error)
      util.showError('加载失败')
    } finally {
      this.setData({ loading: false })
    }
  },

  onPullDownRefresh() {
    this.loadMyRegistrations()
    wx.stopPullDownRefresh()
  },

  // 查看会议详情
  viewActivityDetail(e) {
    const activityId = e.currentTarget.dataset.activityId
    wx.navigateTo({
      url: `/pages/activity/detail/detail?id=${activityId}`
    })
  },

  // 取消报名
  async cancelRegistration(e) {
    const item = e.currentTarget.dataset.item
    
    wx.showModal({
      title: '确认取消',
      content: `确定要取消报名"${item.item_name}"吗？`,
      confirmColor: '#e74c3c',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '取消中...' })
            
            const result = await activityItemApi.cancelRegistration(
              item.activity_id,
              item.item_id,
              item.id
            )

            wx.hideLoading()

            if (result.code === 200 || result.success) {
              util.showSuccess('取消成功')
              // 重新加载列表
              this.loadMyRegistrations()
            } else {
              util.showError(result.message || '取消失败')
            }
          } catch (error) {
            wx.hideLoading()
            console.error('取消报名失败:', error)
            util.showError('取消失败，请重试')
          }
        }
      }
    })
  },

  // 分享给好友/群聊
  onShareAppMessage() {
    return {
      title: '探索语言成长社 - 我的报名',
      path: '/pages/index/index',
      imageUrl: '/assets/images/activity01.jpg'
    }
  }
})

